package com.guigu.health.common;


import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.google.gson.Gson;

import java.io.File;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName:UploadFiles
 * @Description:文件上传工具 类
 * @Author:longtao
 * @Date:2021/4/8
 * @Version:1.0
 */
public class UploadFiles {
    /**
     * 秘钥
     */
    private final static String ACCESSKEY = "xQhbVob_VyjiPEB4dmSaKauvTGL3OuT7flutrTkb";
    private final static String SECRETKEY = "5f34Pn2uNiCIHB1NUiF1zkTcORxKumjFvC2wSDNP";
    /**
     * 存储空间名称
     */
    private final static String BUCKET = "jiangfenghealth";
    /**
     * 域名
     */
    public static final String DOMAIN= "http://qr6xs5ygb.hn-bkt.clouddn.com/";



    private static String getToken() {
        // 创建授权
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        //获得认证后的令牌
        String upToken = auth.uploadToken(BUCKET);
        return upToken;
    }

    private static UploadManager getUploadManager() {
        /**
         * 指定一个带Zone
         * 对象的配置类
         */
        Configuration cfg = new Configuration(Zone.zone2());
        /**
         * 构建上传管理器
         */
        return new UploadManager(cfg);
    }

    private static BucketManager getBucketManager() {
        /**
         * 创建授权信息
         */
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        /**
         * 创建操作某个仓库管理器
         */
        return new BucketManager(auth, new Configuration(Zone.zone2()));
    }

    /**
     * 文件上传
     * @param localFilePath
     * @param savedFilename
     */
    public static void uploadFile(String localFilePath, String savedFilename) {
        UploadManager uploadManager = getUploadManager();
        String upToken = getToken();
        try {
            Response response = uploadManager.put(localFilePath, savedFilename, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(String.format("key=%s, hash=%s", putRet.key, putRet.hash));

        } catch (QiniuException e) {
            Response r = e.response;
            System.err.println(r.toString());
            e.printStackTrace();
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException qiniuException) {
                qiniuException.printStackTrace();
            }
        }
    }

    /**
     * 图片上传
     * @param bytes
     * @param savedFilename
     */
    public static void uploadViaByte(byte[] bytes,String savedFilename){
        UploadManager uploadManager = getUploadManager();
        String upToken = getToken();
        Response response = null;
        try {
            response = uploadManager.put(bytes, savedFilename, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException e) {
                e.printStackTrace();
            }
            ex.printStackTrace();
        }

    }

    /**
     * 批处理删除
     * @param filenames
     * @return
     */
    public static List<String> removeFiles(String... filenames) {
        for (int i = 0; i < filenames.length; i++) {
            System.out.println("filenames[i] = " + filenames[i]);
        }
        /**
         * 删除成功文件的列表
         */
        List<String> list = new ArrayList<String>();
        if (filenames.length > 0) {
            // 创建仓库管理器
            BucketManager bucketManager = getBucketManager();
            // 创建批处理器
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            // 批量删除多个文件
            //单次批量请求的文件数量不得超过1000
            /* batchOperations.addStatOps(BUCKET,filenames);*/
            batchOperations.addDeleteOp(BUCKET, filenames);
            try {
                Response response = bucketManager.batch(batchOperations);
                // 获得批处理的状态
                BatchStatus[] batchStatuses = response.jsonToObject(BatchStatus[].class);
                for (int i = 0; i < filenames.length; i++) {
                    BatchStatus status = batchStatuses[i];
                    String key = filenames[i];
                    if (status.code == 200) {
                        list.add(key);
                        System.out.println("delete success");
                    } else {
                        System.out.println("delete failure");
                    }
                }
            } catch (QiniuException e) {
                e.printStackTrace();
            }
        }
        return list;
    }


    /**
     * 获取所有文件路径
     * @return
     */
    public static BucketManager.FileListIterator getAllFiles(){
        Configuration cfg = new Configuration(Region.region2());
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        String prefix = "";
        int limit = 1000;
        String delimiter = "";
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(BUCKET, prefix, limit, delimiter);
        return fileListIterator;
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        File file=new File("D:\\GuiGu\\S3\\healthProject\\health\\setMeal.xlsx");
    }
}
